package utils

import java.util.regex.Pattern

import archer.student.model.form.LoginValidateCode
import cats.implicits._

import scala.concurrent.ExecutionContext

object ValidateUtil {

  /**
   * 判断一个字符串是否全为中文
   * @param str 输入字符串
   * @return 字符串是否全为中文
   */
  def isChineseByRange(str: String): Boolean = {
    val ch = str.toCharArray()
    ch.forall(c => c >= 0x4E00 && c <= 0x9FBF)
  }

  /**
   * 手机号验证
   *
   * @param  str
   * @return 验证通过返回true
   */
  def isMobile(str: String): Boolean = {
    val p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
    val m = p.matcher(str)
    m.matches()
  }

  import ArcherHelper._

  def confirmEmailAndEnable(code: String, singinValidateCookie: String)(
    implicit
    ec: ExecutionContext): V.ResultT[Boolean] = {
    val modelOpt = LoginValidateCode.fromString(singinValidateCookie)
    etLess.lift {
      val codeInfo = etLess.unlift(V.fromOption(modelOpt, ErrorResult("参数错误")))
      //2 分钟有效
      val exceptionMillions = System.currentTimeMillis() - (2 * 60 * 1000)
      val resultT =
        if (exceptionMillions > codeInfo.currentMillions)
          V.leftT[Boolean](ErrorResult("验证码超时"))
        else if (code.toUpperCase === codeInfo.code.toUpperCase)
          V.rightT(true)
        else
          V.leftT[Boolean](ErrorResult("验证码错误"))
      etLess.unlift(resultT)
    }
  }

}
